/**
 * 
 */
package com.kinglone.common.shiro;

import com.kinglone.back.role.service.RoleService;
import com.kinglone.back.sysmenu.service.SysMenuService;
import com.kinglone.back.user.controller.LoginController;
import com.kinglone.back.user.model.User;
import com.kinglone.back.user.service.UserService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**  
* Copyright (C),2017, Guangzhou sys info. Co., Ltd.
* @ClassName: MyRealm  
* @Description: shiro 认证 + 授权   重写 
* @author lao  
* @date 2017年12月28日上午10:17:54  
* @version 1.00 
*/
public class MyRealm extends AuthorizingRealm {
	
	protected final static Logger logger = LogManager.getLogger(LoginController.class);

	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private SysMenuService sysMenuService;
	
	/**
	 * 授权Realm
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		logger.info("------------------进入授权-------------------");
		//获取用户账号
		String account = (String)principals.getPrimaryPrincipal();
		User user = userService.getUserByAccount(account);
		String[] roleArray = user.getRoleid().split(",");
		Set<String> roleNameSet = new HashSet<String>();//角色名称组
		Set<String> permissionSet = new HashSet<String>();//权限组

		for(String roleId : roleArray){
			String roleName = roleService.getRoleNameByRoleId(Integer.valueOf(roleId));
			roleNameSet.add(roleName);

            List<String> permissions = sysMenuService.getPermissionByRoleId(roleId);
			if(permissions != null){
			    for(String permission : permissions){
                    permissionSet.add(permission);
                }
            }
		}

		SimpleAuthorizationInfo info =  new SimpleAuthorizationInfo();
		/**根据用户ID查询角色（role），放入到Authorization里.*/
		info.setRoles(roleNameSet);
		/**根据用户ID查询权限（permission），放入到Authorization里.*/
		info.setStringPermissions(permissionSet);
        return info;
	}

	/**
	 * 登录认证Realm
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) {
		String username = (String)token.getPrincipal();
		String password = new String((char[])token.getCredentials());
		User user = userService.login(username, password);


		//**密码加盐**交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配
		return new SimpleAuthenticationInfo(user.getAccount(),user.getPassword(),ByteSource.Util.bytes("3.14159"), getName());
	}

	//https://blog.csdn.net/LHacker/article/details/19340757


	public void clearAllCache() {
		clearAllCachedAuthenticationInfo();
		clearAllCachedAuthorizationInfo();
	}

	public void clearAllCachedAuthorizationInfo() {
		getAuthorizationCache().clear();
	}

	public void clearAllCachedAuthenticationInfo() {
		getAuthenticationCache().clear();
	}

	@Override
	public void clearCachedAuthorizationInfo(PrincipalCollection principals) {
		super.clearCachedAuthorizationInfo(principals);
	}

	@Override
	public void clearCachedAuthenticationInfo(PrincipalCollection principals) {
		super.clearCachedAuthenticationInfo(principals);
	}

	@Override
	public void clearCache(PrincipalCollection principals) {
		super.clearCache(principals);
	}
}
